<template>
    <el-container class="layoutWrap" v-if="isLoadSuc">
        <!--侧边栏-->
        <sidebar 
            :routeConfig="routeConfigArr" 
            @rightClick="rightClick"
            ref="sideBarRef">
        </sidebar>
        <el-container>
            <!--头部-->
            <el-header class="layoutHeader">
                <useHeader 
                    @headSelectTem="showSelectTemMet"
                    @selectSetArea="selectSetAreaMet"
                    @manageDetailPage="manageDetailPageMet"
                    @creataDetail="creataDetailMet"
                    ref="useHeader"
                    @isCollapse="isCollapseMet">
                </useHeader>
            </el-header>
            <!--tag区域-->
            <tag
                ref="tag"
                :nowItem="nowItem"
                :routeConfig="routeConfigArr" >
            </tag>
            <!--内容区域-->
            <el-main>
                <div class="mainBg">
                    <component :is="componentPanel" />
                </div>
            </el-main>
        </el-container>
        <!--右键按钮-->
        <rightBtn 
            v-if="rightBtnShow" 
            :item = "nowRightClickItem"
            :position="rightEvent">
        </rightBtn>
        <!--新建页面弹窗-->
        <createRouter 
            :createPageType="createPageType"
            v-if="createRouterShow">
        </createRouter>
        <!--删除-->
        <el-dialog
            v-model="dialogVisible"
            title="删除"
            width="30%"
        >
            <span>确定要删除该目录吗?该目录下的所有子目录将一并删除!</span>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmDelete">确认</el-button>
            </span>
            </template>
        </el-dialog>
        <!--选择模版-->
        <selectTem
            v-if="showSelectTem"
            @changeSelectTem="changeSelectTemMet"
            @confrimTem="confrimTemMet"
            @cancelTem="cancelTemMet">
        </selectTem>
        <!--选择区域-->
        <setArea 
            v-if="showSetArea"
            @setAreaChange="setAreaChangeMet"
            @cancelSetArea="cancelSetAreaMet">
        </setArea>
        <!--管理详情页-->
        <sideBarDetail 
            v-if="showSideBarDetail"
            @toDetailPage="toDetailPageMet"
            @cancelSidebarDetail= "showSideBarDetail = false">
        </sideBarDetail>
        <!--编辑区域-->
        <div class="editArea" v-if="showComponentEdit">
            <component :type="editType" :is="componentEdit" />
        </div>
    </el-container>
</template>
<script type="text/javascript">
import { markRaw } from 'vue';
//侧边栏
import sidebar from "./sidebar/index.vue";
//头部导航栏
import useHeader from "./header/index.vue";
//导航栏区域
import tag from './tag.vue';
//右键按钮
import rightBtn from "@/layouts/right/index.vue";
//欢迎页面
import index from "./assist/index.vue";
//路由配置
// import routeConfig  from "@/router/routerConfig.json";
import createRouter from "@/layouts/right/createRouter.vue";
//选择模版
import selectTem from "@/layouts/function/selectTem.vue";
//设置区域
import setArea from "@/layouts/function/setArea.vue";
//管理详情页
import sideBarDetail from "@/layouts/function/sideBarDetail.vue";
//使用pinia
import useRoute  from '@/store/route.js'
import useProject  from '@/store/project.js'
import { mapState,mapActions } from 'pinia';
//
var useRouteJsonArr = true;
export default{
    inject: ['reload'],
    data () {
        return {
            rightBtnShow:false,
            rightEvent:{},
            routeConfigArr:[],
            createRouterShow:false,
            componentPanel:null,
            componentEdit:null,
            showComponentEdit:false,
            nowPageItem:{},
            showSelectTem:false,
            showSetArea:false,
            showSideBarDetail:false,
            editType:"",
            templatePath:{
                templatePage:"../view/template",
                templateEditPage:"./function"
            },
            templateModule:{},
            templateEditModule:{},
            nowRightClickItem:{},
            newCreateItem:{},
            dialogVisible:false,
            isLoadSuc:false,
            isPackaged:false,
            createPageType:"",
        }
    },
    beforeRouteEnter(to, from) {
        if(from.name == 'project'){
            useRouteJsonArr = true;
        }else{
            useRouteJsonArr = false;
        }
        window.onbeforeunload = (e) => {
            return undefined
        }
    },
    computed: {
        ...mapState(useRoute, ['routeConfig','nowItem']),
        ...mapState(useProject, ['isEditModel','setPreviewModel']),
    },
    beforeCreate() {
        this.$mitt.all.clear();
    },
    async created() {
        //当前项目
        this.isLoadSuc = false;
        this.$mitt.on("rightClick",this.rightClickDeal);
        this.$mitt.on("closeDialog",this.closeDialog);
        this.$mitt.on("confrimDialog",this.confrimDialog);
        this.$mitt.on("confrimDetailDialog",this.confrimDetailDialog);
        this.$mitt.on("sideBarClick",this.sideBarClick);
        this.$mitt.on("sideBarRightClick",this.sideBarRightClick);
        this.$mitt.on("tagClick",this.sideBarClick);
        this.$mitt.on("templateSelect",this.templateSelect);
        this.$mitt.on("showEditComponent",this.showEditComponent);
        this.$mitt.on("onlyRefreshComponent",this.onlyRefreshComponent);
        this.$mitt.on("closeEditComponent",this.closeEditComponent);
        //加载所有模版
        this.templateModule = import.meta.glob('../view/template/*.vue',{ eager: true });
        this.templateEditModule = import.meta.glob('./function/*.vue',{ eager: true });
        this.isPackaged = await window.preload.isPackaged();
        //判断路由跳转
        if(useRouteJsonArr){
            //从项目页面而来
            this.routeConfigArr = await this.$util.native.loadRouterConfig(); 
            this.saveRouteConfig(this.routeConfigArr);
            if(this.nowItem && this.nowItem.name){
                this.jumpPage(this.nowItem);
                this.nowPageItem = this.nowItem;
            }else{
                this.jumpPage({path:"/index"});
                this.nowPageItem = undefined;
                this.saveNowItem({path:"/index"});
            }
        }else{
            //刷新而来
            this.routeConfigArr = this.routeConfig;
            if(this.nowItem && this.nowItem.name){
                 //跳转页面
                this.jumpPage(this.nowItem);
                this.nowPageItem = this.nowItem;
            }else{
                this.jumpPage({path:"/index"});
                this.nowPageItem = undefined;
                this.saveNowItem({path:"/index"});
            }
        }
        this.isLoadSuc = true;
        //设置高亮
        if(typeof this.nowPageItem != 'undefined'){
            var _this = this;
            setTimeout(() => {
                _this.$refs.sideBarRef.setHighSidebar(this.nowPageItem);
            }, 100);
        }
        //重置关闭按钮
        this.resetClose();
    },
    unmounted() {
        this.$mitt.all.clear();
    },
    watch:{
        
    },
    components : {
        sidebar,
        useHeader,
        tag,
        rightBtn,
        createRouter,
        index,
        selectTem,
        setArea,
        sideBarDetail,
    },
    methods : {
        ...mapActions(useRoute, ['saveRouteConfig','saveNowItem']),
        isCollapseMet(isCollapse){
            this.$refs.sideBarRef.collapseMet(isCollapse);
        },
        resetClose(){
            let isRefresh = false;
            let keyArr = [];
            document.onkeydown = function (event) {
                if(event.key == 'r'){
                    window.onbeforeunload = (event) => {
                        return undefined;
                    }
                }
            }
            window.onbeforeunload = async (event) => {
                if(this.$route.name == 'panel'){
                    event.returnValue = false;
                    this.saveNowItem({});
                    await window.preload.setMainWinSizeSmall();
                    this.$router.push({name:"project"});
                    //设置模式为：编辑模式
                    this.setPreviewModel(true);
                }
            }
        },
        jumpPage(item){
            //加载页面
            if(item && item.name){
                this.$util.native.readJson(item).then( component => {
                    this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${component.type}.vue`].default);
                })
            }else{
                //首页
                this.componentPanel = markRaw(index);
            }
        },
        sideBarClick(item){
            this.nowPageItem = item;
            this.saveNowItem(item);
            this.componentPanel = null;
            if(item.path == '/index'){
                this.componentPanel = markRaw(index);
            }else{
                this.$util.native.readJson(item).then( component => {
                    this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${component.type}.vue`].default);
                })
            }
            //控制tag标签
            this.$refs.tag.getPageInfo();
            //关闭选择组件
            this.resetShow();
        },
        sideBarRightClick(params){
            if(!this.isEditModel){
                return;
            }
            //侧边栏item区域点击
            this.rightBtnShow = true;
            this.rightEvent = params.event;
            this.nowRightClickItem = params.item;
        },
        rightClick(event){
            if(!this.isEditModel){
                return;
            }
            //侧边栏空白区域点击
            this.rightBtnShow = true;
            this.rightEvent = event;
            this.nowRightClickItem = {};
        },
        rightClickDeal(params){
            //打开新建页面弹窗
            this.rightBtnShow = false;
            if(params == 'createChapter'){
                //新建侧边栏页面
                this.createPageType = 'sidebar';
                this.createRouterShow = true;
            }else if(params == 'delete'){
                //删除
                this.dialogVisible = true;
            }
        },
        closeDialog(){
            this.createRouterShow = false;
        },
        async confrimDialog(params){
            //新建页面弹窗确认
            this.createRouterShow = false;
            //1.创建文件
            const result = await this.$util.native.createNativeFile(params.name);
            //2.创建路由JSON信息数据：空白、章节、节点
            const useResult = this.$util.native.createRouteObj(params);
            if(JSON.stringify(this.nowRightClickItem) == '{}'){
                //空白点击：新增页面
                //3.添加路由JSON信息数据
                this.routeConfigArr.push(useResult);
            }else if(typeof this.nowRightClickItem.name != 'undefined'){
                //节点点击：新增页面，并将此节点改换为章节
                const changeItem = await this.$util.native.changeRouteObj(this.nowRightClickItem);
                //修改路由信息
                useResult.path = changeItem.path + useResult.path;
                useResult.component = `() => import('@/view${useResult.path}.vue')`;
                changeItem.secMenu.push(useResult);
                //更换json信息
                //将树形结构转化为数组
                let treeToArrayArr = this.$util.treeToArray(this.routeConfigArr);
                //找到此节点在数组中的位置
                let infoPosition = this.$util.array_getObjPosition(treeToArrayArr,changeItem);
                //设置json信息的父路径
                if(typeof treeToArrayArr[infoPosition].fatherPath != 'undefined'){
                    changeItem.fatherPath = treeToArrayArr[infoPosition].fatherPath;
                }
                //替换数组中的此信息
                treeToArrayArr.splice(infoPosition,1,changeItem);
                //3.添加路由JSON信息数据，将数组转化为树形结构
                this.routeConfigArr = this.$util.arrayToTree(treeToArrayArr);
            }else{
                //章节点击：新增页面，将要新增的页面
                //3.添加路由JSON信息数据
                //将树形结构转化为数组
                let treeToArrayArr = this.$util.treeToArray(this.routeConfigArr);
                //将新建节点添加父节点，并添加
                useResult.fatherPath = this.nowRightClickItem.path;
                //修改路由信息
                useResult.path = this.nowRightClickItem.path + useResult.path;
                useResult.component = `() => import('@/view${useResult.path}.vue')`;
                treeToArrayArr.push(useResult);
                //将数组转化为树形结构
                this.routeConfigArr = this.$util.arrayToTree(treeToArrayArr);
            }
            //4.修改同步json文件下数据结构
            const formatResult = await this.$util.native.formatRouteConfig(useResult,this.nowRightClickItem);
            //5.存储路由json信息
            this.saveRouteConfig(this.routeConfigArr);
            //6.保存将要跳转的页面
            this.saveNowItem(useResult);
            //7.写入路由json信息文件
            await this.$util.native.rewriteRouteConfig(formatResult);
            //刷新
            this.reload();
        },
        async confirmDelete(){
            //删除功能
            this.dialogVisible = false;
            if(typeof this.nowRightClickItem.name != 'undefined'){
                //节点点击：删除此节点,
                /***
                 * 是否有父节点：
                 * 无父节点：直接删除，
                 * 有父节点：
                 * 是否有兄弟节点：
                 * 有：只删除当前节点，
                 * 无：删除此节点，并改变父节点的类型
                 * */
                //将树形结构转化为数组
                let treeToArrayArr = this.$util.treeToArray(this.routeConfigArr);
                //找到此节点在数组中的位置
                let infoPosition = this.$util.array_getObjPosition(treeToArrayArr,this.nowRightClickItem);
                //删除数组中的此信息
                let nowArrInItem = treeToArrayArr[infoPosition];
                if(typeof nowArrInItem.fatherPath != 'undefined'){
                    //有父亲节点：判断是否有兄弟节点
                    if(this.$util.array_nodeNum(treeToArrayArr,nowArrInItem) >= 2){
                        //有兄弟节点
                        treeToArrayArr.splice(infoPosition,1);
                    }else{
                        //无兄弟节点：删除此节点，并且将父节点从章节转为为节点：
                        let fatherItem = this.$util.arr_findItem(treeToArrayArr,nowArrInItem.fatherPath);
                        //找到父节点：将父节点从章节转为为节点
                        let newFatherItem = this.$util.native.nodeToItemObj(fatherItem);
                        newFatherItem.fatherPath = fatherItem.fatherPath;
                        //替换称新的对象，找到此父节点在数组中的位置
                        //删除此节点
                        treeToArrayArr.splice(infoPosition,1);
                        //找到此父节点位置，并进行替换
                        let infoFatherPosition = this.$util.array_getObjPosition(treeToArrayArr,fatherItem);
                        treeToArrayArr.splice(infoFatherPosition,1,newFatherItem);
                    }
                }else{
                    //无父亲节点
                    treeToArrayArr.splice(infoPosition,1);
                }
                //3.添加路由JSON信息数据，将数组转化为树形结构
                this.routeConfigArr = this.$util.arrayToTree(JSON.parse(JSON.stringify(treeToArrayArr)));
            }else{
                //章节点击：删除全部章节
                /***
                 * 是否有父节点：
                 * 无父节点：从最外侧删除，
                 * 有父节点：
                 * 是否有兄弟节点：
                 * 有：只删除当前节点，
                 * 无：删除此节点，并改变父节点的类型
                 * 
                 * */
                //获取此章节数组
                //将树形结构转化为数组
                let treeToArrayArr = this.$util.treeToArray(this.routeConfigArr);
                //找到此节点在数组中的位置
                let infoPosition = this.$util.array_getObjPosition(treeToArrayArr,this.nowRightClickItem);
                let nowArrInItem = treeToArrayArr[infoPosition];
                if(typeof nowArrInItem.fatherPath != 'undefined'){
                    //有父亲节点，获取所有子节点
                    let allChildNode = this.$util.getAllChild(this.routeConfigArr,nowArrInItem.path,[]);
                    //将本身节点加入到数组中
                    allChildNode.push({path:nowArrInItem.path})
                    let saveArr = this.$util.array_deleteAllItem(allChildNode,treeToArrayArr);
                    //将数组转化为树形结构
                    this.routeConfigArr = this.$util.arrayToTree(JSON.parse(JSON.stringify(saveArr)));
                    //有父亲节点：判断是否有兄弟节点
                    if(this.$util.array_nodeNum(treeToArrayArr,nowArrInItem) < 2){
                        //无兄弟节点，将父章节转化为节点
                        let fatherItem = this.$util.arr_findItem(treeToArrayArr,nowArrInItem.fatherPath);
                        let newFatherItem = this.$util.native.nodeToItemObj(fatherItem);
                        newFatherItem.fatherPath = fatherItem.fatherPath;
                        //找到此父节点位置，并进行替换
                        let infoFatherPosition = this.$util.array_getObjPosition(treeToArrayArr,fatherItem);
                        treeToArrayArr.splice(infoFatherPosition,1,newFatherItem);
                    }
                }else{
                    //无父亲节点
                    let chapterIndex = this.$util.array_getObjPosition(this.routeConfigArr,this.nowRightClickItem);
                    //删除树形结构中的数据
                    this.routeConfigArr.splice(chapterIndex,1)
                }
            }
            //4.修改同步json文件下数据结构
            const formatResult = await this.$util.native.deleteRouteConfig(this.nowRightClickItem);
            //5.存储路由json信息
            this.saveRouteConfig(this.routeConfigArr);
            //6.保存将要跳转的页面
            this.saveNowItem({});
            //7.写入路由json信息文件
            await this.$util.native.rewriteRouteConfig(formatResult);
            //刷新
            this.reload();
        },
        templateSelect(){
            //确定更换模版
            this.$util.native.readJson(this.nowPageItem).then( component => {
                this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${component.type}.vue`].default);
            })
        },
        showSelectTemMet(){
            //显示是否更换模版
            this.showSelectTem = true;
        },
        cancelTemMet(){
            //取消模版选择
            this.$util.native.readJson(this.nowPageItem).then( component => {
                this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${component.type}.vue`].default);
            })
            this.showSelectTem = false;
        },
        changeSelectTemMet(type){
            this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${type}.vue`].default);
        },
        //更改页面模版类型
        async confrimTemMet(type){
            //修改json模版数据到json文件
            await this.$util.native.changeNativeTem(this.nowPageItem,type);
            //重新加载模版
            this.$util.native.readJson(this.nowPageItem).then( component => {
                this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${component.type}.vue`].default);
            })
            //重置头部
            this.$refs.useHeader.showBtnAreaMet();
            //关闭选择组件
            this.resetShow();
        },
        selectSetAreaMet(){
            this.showSetArea = true;
        },
        manageDetailPageMet(){
            this.showSideBarDetail = true;
        },
        cancelSetAreaMet(){
            this.$mitt.emit('cancelSetArea');
            this.showSetArea = false;
        },
        resetShow(){
            this.showSetArea = false;
            this.showSelectTem = false;
            this.showComponentEdit = false;
            this.showSideBarDetail = false;
        },
        setAreaChangeMet(params){
            this.$mitt.emit("setAreaChange",params);
        },
        /***********编辑区域：开始*********/
        showEditComponent(params){
            this.editType = params.type;
            this.componentEdit = null;
            this.showComponentEdit = true;
            var _this = this;
            setTimeout(() => {
                _this.componentEdit = markRaw(_this.templateEditModule[`${_this.templatePath.templateEditPage}/${params.component}.vue`].default);
            }, 100);
        },
        closeEditComponent(){
            this.showComponentEdit = false;
        },
        /***********编辑区域：结束*********/
        onlyRefreshComponent(){
            this.componentPanel = null;
            this.$util.native.readJson(this.nowPageItem).then( component => {
                this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${component.type}.vue`].default);
            })
        },
        creataDetailMet(){
            //新建详情页面
            this.createPageType = 'detail';
            this.createRouterShow = true;
        },
        async confrimDetailDialog(params){
            //隐藏
            this.createRouterShow = false;
            //1.创建文件
            await this.$util.native.createDetailFile(params.name);
            //2.创建路由JSON信息数据
            const useResult = this.$util.native.createDetailRouteObj(params);
            //4.写入路由json信息文件
            const routerDetail = await this.$util.native.readRouterDetailJson();
            routerDetail.push(useResult)
            await this.$util.native.rewriteDetailRoute(routerDetail);
            //5.跳转页面
            this.toDetailPageMet(useResult);
            //关闭选择组件
            this.resetShow();
        },
        toDetailPageMet(item){
            //
            this.nowPageItem = item;
            this.saveNowItem(item);
            //
            this.componentPanel = null;
            this.$util.native.readJson(item).then( component => {
                this.componentPanel = markRaw(this.templateModule[`${this.templatePath.templatePage}/${component.type}.vue`].default);
            });
            //刷新
            this.reload();
        }
    }
}
</script>
<style lang="less">
	.layoutWrap {
        .pageCover();
        min-width: 1150px !important;
        .el-sub-menu__icon-arrow {
            position: absolute !important;
        }
        > span {
            display: inline-block;
            margin: 0 10px;
            font-size: 14px;
        }
        .layoutHeader{
            border-bottom: 1px solid #f1f2f3;
        }
        .el-main{
            background:#F2F3F5;
            padding-top: 0px;
        }
        .mainBg{
            background:white;
            padding:15px;
            border-radius:5px;
        }
        .editArea{
            position: absolute;
            right: 0;
            top: 0;
            bottom: 0;
            background-color: white;
            z-index: 10;
            padding: 10px;
            overflow-y: scroll;
        }
    }
</style>
